let express = require("express");

let { Order, Cart } = require("../../model/index.js");

// ****1-创建一个路由中间件，来管理 文章相关的路由

let router = express.Router();

// ****2-在文章路由中间件 处理 文章相关的路由操作
const alipayConfig = require("../../alipay_config.js");

const AlipaySdk = require("alipay-sdk").default;
const alipaySdk = new AlipaySdk(alipayConfig.AlipayBaseConfig);

router.get("/pay/:order_id", async (req, res) => {
  let order = await Order.findById(req.params.order_id);
  console.log(order);
  const result = await alipaySdk.pageExec("alipay.trade.page.pay", {
    bizContent: {
      // 商家自定义订单号，每次测试都要改一次，不能重复
      out_trade_no: Date.now(),
      // 支付金额
      total_amount: order.countPirce,
      subject: "测试订单",
      product_code: "FAST_INSTANT_TRADE_PAY",
    },
  });
  console.log(result);
  res.send(result);
});

// 添加购物车 参数 cart_ids[''c1','c2']
router.post("/", async (req, res) => {
  console.log(req.body);
  // let cartArr = req.body.cart_ids;
  let productArr = [];
  let countNum = 0;
  let countPrice = 0;
  let cartArr = await Cart.find({ uid: req.auth.id, checked: true }).populate(
    "pid"
  );
  cartArr = cartArr.filter((v) => v.pid != null);
  console.log(JSON.stringify(cartArr));
  cartArr.forEach((cartObj) => {
    // console.log(cart_id);
    // let cartObj = await Cart.findById(cart_id).populate("pid").exec();
    productArr.push(cartObj.pid);
    // productArr.push(cartObj.pnum);
    countNum += cartObj.pnum;
    countPrice += cartObj.pnum * cartObj.pid.price;
    console.log(cartObj.pnum * cartObj.pid.price);
    // productArr.push
  });
  console.log(cartArr);
  // console.log(productArr);
  // console.log(countNum);
  // console.log(countPrice);
  await Order.create({
    uid: req.auth.id,
    products: productArr,
    countNum: countNum,
    countPirce: countPrice,
    // orderNum:Date.now()
  }).then((r) => {
    // console.log(r);
    res.json({
      code: 1,
      data: r,
    });
  });

  console.log(req.body);
});

// ******3-导出文章路由中间件
module.exports = router;
